package com.desire.fallback;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: 回退机制配置
 * @Author: k23
 * @Date: 2022-06-10 10:34
 * @Version: 1.0
 */
public class ServiceFallBack implements FallbackProvider {
    @Override
    public String getRoute() {
        //表明为哪个微服务提供回退，return "*"代表为所有微服务提供回退
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                //返回http状态
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "ok";
            }

            @Override
            public void close() {

            }

            /**
             * 回退处理返回的内容
             * @return
             * @throws IOException
             */
            @Override
            public InputStream getBody() throws IOException {
                //响应体
                String msg = "{code:0,msg:'服务不可用,返回的默认数据'}";
                return new ByteArrayInputStream(msg.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                //返回头的设置
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                return httpHeaders;
            }
        };
    }
}
